const   Router = require('koa-router')
const mongoose = require('mongoose')

let router = new Router()

router.post('/category',async(ctx)=>{
    //取得Model
    const Category = mongoose.model('Category')
    //把从前端接收的POST数据封装成一个新的Category对象
    console.log(ctx.request.body)
    let newCategory = new Category(ctx.request.body)
    //用mongoose的save方法直接存储，然后判断是否成功，返回相应的结果
    await newCategory.save().then(()=>{
        //成功返回code=200，并返回成功信息
        ctx.body={
            code:200,
            message:'提交成功'
        }
    }).catch(error=>{
         //失败返回code=500，并返回错误信息
        ctx.body={
            code:500,
            message:error
        }
    })
})
//查询分类表
router.post('/categoryList', async (ctx)=>{
    const Category = mongoose.model('Category')

    await Category.find({}).exec().then( async (result)=>{
        ctx.body = {
            code:200,
            message:result
        }
    }).catch(err=>{
        console.log(err)
        ctx.body = {
            code:500,
            message:err
        }
    })
})
//根据id删除分类
router.post('/delect', async(ctx)=>{
    const Category = mongoose.model('Category')
        //等待前台传过来id
    let CategoryId = ctx.request.body.CategoryId
    console.log(CategoryId)
    await Category.deleteOne({"_id":CategoryId}).exec().then(result=>{
        ctx.body = {
            code:200,
            message:result
        }
    }).catch(err=>{
        console.log(err)
        ctx.body = {
            code:500,
            message:err
        }
    })
    
})

module.exports = router